package com.wstuo.common.rules.dao;

import java.util.List;

import com.wstuo.common.rules.dto.RuleQueryDTO;
import com.wstuo.common.rules.entity.Rule;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.util.DaoUtils;
import com.wstuo.common.util.StringUtils;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

/**
 * dao of rule
 * 
 * @author <a href="mailto:376890523@qq.com">jeff</a>
 * @version 0.1 2010.9.28
 * */
public class RuleDAO extends BaseDAOImplHibernate<Rule> implements IRuleDAO {
	/**
	 * 分页查询规则
	 * 
	 * @param qdto
	 * @param start
	 * @param limit
	 * @param sidx
	 * @param sord
	 * @return PageDTO
	 */
	public PageDTO findPager(RuleQueryDTO qdto, int start, int limit, String sidx, String sord) {
		DetachedCriteria dc = DetachedCriteria.forClass(Rule.class);
		if (qdto != null) {
			if (qdto.getRulePackageNo() != null) {
				dc.createAlias("rulePackage", "package").add(Restrictions.eq("package.rulePackageNo", qdto.getRulePackageNo()));
			}
			if (qdto.getPackageName() != null) {
				dc.createAlias("rulePackage", "packages").add(Restrictions.eq("packages.packageName", qdto.getPackageName()));
			}
			if (qdto.getFlagName() != null) {
				String[] flags=qdto.getFlagName().split(",");
				dc.createAlias("rulePackage", "packagef").add(Restrictions.in("packagef.flagName", flags));
			}
			if (StringUtils.hasText(qdto.getRuleName())) {
				dc.add(Restrictions.like("ruleName", qdto.getRuleName(), MatchMode.ANYWHERE));
			}
			if (StringUtils.hasText(qdto.getDescription())) {
				dc.add(Restrictions.like("description", qdto.getDescription(), MatchMode.ANYWHERE));
			}
		}
		// 排序
		dc = DaoUtils.orderBy(sidx, sord, dc);
		return super.findPageByCriteria(dc, start, limit);
	}

	/**
	 * 根据SLA ID查询规则列表
	 * 
	 * @param id
	 *            SLAId
	 * @return list rule
	 */
	@SuppressWarnings("unchecked")
	public List<Rule> findRuleList(Long id) {
		final DetachedCriteria dc = DetachedCriteria.forClass(Rule.class);
		dc.createAlias("rulePackage", "package").add(Restrictions.eq("package.rulePackageNo", id));
		return super.getHibernateTemplate().findByCriteria(dc);
	}

	/**
	 * 根据规则名称查询
	 * 
	 * @param id
	 * @param ruleName
	 * @return List<Rule>
	 */
	@SuppressWarnings("unchecked")
	public List<Rule> existRuleName(Long id, String ruleName) {
		final DetachedCriteria dc = DetachedCriteria.forClass(Rule.class);
		dc.createAlias("rulePackage", "package").add(Restrictions.eq("package.rulePackageNo", id));
		dc.add(Restrictions.eq("ruleName", ruleName));
		return super.getHibernateTemplate().findByCriteria(dc);
	}
}
